package org.carpediem.conman.rest;

import com.sun.jersey.multipart.BodyPart;
import com.sun.jersey.multipart.BodyPartEntity;
import com.sun.jersey.multipart.MultiPart;
import static org.apache.commons.io.IOUtils.toByteArray;
import org.carpediem.conman.api.ConMan;
import org.carpediem.conman.entity.Contact;
import org.carpediem.conman.entity.ContactBag;
import org.carpediem.schema.conman.ContactInfo;

import javax.servlet.ServletContext;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.logging.Logger;

/**
 * @author Mark Petrovic
 */
@Path("/contacts")
final public class ContactsResource extends AbstractResource {
    private final static Logger logger = Logger.getLogger(ContactsResource.class.getName());

    public ContactsResource(@Context UriInfo uriInfo, @Context ServletContext servletContext) {
        super(uriInfo, servletContext);
    }

    @GET
    @Produces(MediaType.APPLICATION_XML)
    public ContactBag getContacts() {
        List<Contact> contacts = contactDao.getAllContacts();
        return entityToBag(contacts, ContactBag.class);
    }

    /**
     * Post a ContactInfo and an optional set of binary documents
     *
     * @param multiPart
     * @return Jersey Response
     * @throws IOException
     */
    @POST
    @Consumes(ConMan.MULTIPART_MIXED)
    @Produces(MediaType.APPLICATION_XML)
    public Response newContact(MultiPart multiPart) throws IOException {

        requireMultiParts(multiPart);

        List<BodyPart> bodyParts = multiPart.getBodyParts();
        ContactInfo cInfo = bodyParts.get(0).getEntityAs(ContactInfo.class);

        requireNewContact(cInfo.getContact().getEmailAddress());

        // Todo: bounds check
        BodyPartEntity bpe = (BodyPartEntity) multiPart.getBodyParts().get(1).getEntity();
        InputStream stream = bpe.getInputStream();
        byte[] buf = toByteArray(stream);

        multiPart.cleanup();

        Contact contact = contactDao.add(cInfo, buf);
        return Response.created(uri(contact)).entity(contact).build();
    }

}
